# 实现栈

# 耦合度     有密切的关系   解耦
import redis
import json

# 声明redis服务器配置
myredis = {
    0: {'host': '127.0.0.1', 'post': 6379},
    1: {'host': '192.168.99.100', 'post': 6380},
}


# 根据用户id进行分配
# redis_id = hash(uid % len(myredis))


class MyStacks:
    def __init__(self):
        self.r = redis.Redis(decode_responses=True)
        self.c = redis.Redis(host='192.168.99.100', port=6380, decode_responses=True)

    # 入栈         uid   数据信息
    def push(self, key, item):

        items = json.loads(item)
        uid = int(items['uid'])
        # print(time, type(time))
        res = hash(uid & 1)
        # print(res)
        try:
            if res == 1:
                self.r.rpush(key, item)
            else:
                self.c.rpush(key, item)
        except Exception as e:
            self.r.delete(key)
            self.r.rpush(key, item)

    # 栈全部数据
    def lrange(self, key):

        list1 = self.r.lrange(key, 0, -1)
        list2 = self.c.lrange(key, 0, -1)
        list3 = []
        for i in list1:
            list3.append(json.loads(i))
        for i in list2:
            list3.append(json.loads(i))
        # print(list3)
        # lambda
        list3.sort(key=lambda x: x['time'])
        return json.dumps(list3)

    # 出栈    撤回
    def pop(self, key, id):
        res = hash(int(id) & 1)
        if res == 1:
            self.r.rpop(key)
        else:
            self.c.rpop(key)

# mystack = MyStacks()
# res = mystack.lrange('send')
# print(json.loads(res))
# for i in json.loads(res):
#     print(i)
# print(mystack.push('send',
#                    '{"uid": "28", "state": 0, "id": "28", "username": "2", "send": {"filename": "12", "type": "text"}, "time": 1639710220.0183673}'))
